package com.example.profile;

import lombok.ToString;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.context.ContextLoaderListener;

/**
 * Profile 多环境配置功能
 */
public class Example {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext =
                new AnnotationConfigApplicationContext();
        applicationContext.getEnvironment().setActiveProfiles(
                "dev"
        );
        applicationContext.register(ProfileConfig.class);
        applicationContext.refresh();

        applicationContext.getBeansOfType(ProfileBean.class)
                .forEach((beanName, bean) -> System.out.println("bean = " + bean));
        applicationContext.close();
    }

    @Configuration
    static class ProfileConfig {

        @Bean
        @Profile("dev")
        public ProfileBean dev() {
            ProfileBean bean = new ProfileBean();
            bean.setName("dev");
            return bean;
        }
        @Bean
        @Profile("test")
        public ProfileBean test() {
            ProfileBean bean = new ProfileBean();
            bean.setName("test");
            return bean;
        }
    }

    @ToString
    static class ProfileBean {
        private String name;

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }
}
